# -*- coding: UTF-8 -*-
# @Time : 2022/1/17 0017 17:16
# @Author : lyw
# @Remark :
import logging

from mxsoftpy.exception import DBError

from db.common.IOTManager.Janitor.janitor_base import JanitorBase
from utils.classes.custom_exception import VerifyError
from index import _


class GetRECDoorDB(JanitorBase):

    def query_rec_door(self, is_switch=None, **kwargs):
        """
        查找未采集的door
        @param is_switch:
        @param kwargs:
        @return:
        """
        filed = ["auth_method", "label", "host", "model_id", "device_id"]
        result_list = []
        if not is_switch:
            door_list = self.select_rec_door(**kwargs)
        else:
            door_list = is_switch
        if door_list:
            door_data = self.tree.open("Janitor", "rec_door", file="IOT").sub_items(key_list=door_list, prop_list=filed)
            for key, value in door_data.items():
                if not is_switch:
                    door_id = str(key).rsplit(".", 1)
                    value["id"] = door_id[1] if len(door_id) >= 2 else key
                    brand_data, brand_sub_data = self.query_brand(value["model_id"])
                    value["brand"] = brand_data["label"]
                    value["auth_method"] = ",".join(
                        [brand_sub_data["auth_method"][i] if brand_sub_data["auth_method"].get(i) else "" for i in
                         value["auth_method"].split(",") if i != ""])
                    value["desc"] = ""
                else:
                    value["rec_id"] = key

                result_list.append(value)
        return result_list

    def select_rec_door(self, **kwargs):
        _, door_list = self.tree.open("Janitor", "rec_door", file="IOT").filter(**kwargs)
        return door_list


class SelectDoorDB(GetRECDoorDB):

    def open_door(self):
        self.tree.open("Janitor", "door", file="IOT")

    def create(self, **kwargs):
        sub_key = self.tree.open("Janitor", "door", file="IOT").insert_sub_keys("")
        self.tree.open("Janitor", "door" + "\\" + sub_key, file="IOT").insert_items(
            [(k, v) for k, v in kwargs.items()])
        return sub_key

    def update(self, sub_key, **kwargs):
        self.tree.open("Janitor", "door\\%s" % sub_key, file="IOT").insert_items(
            [(k, v) for k, v in kwargs.items()])
        return sub_key

    def update_origin(self, sub_key, **kwargs):

        self.tree.open("Janitor", "data_origin\\%s" % sub_key, file="IOT").insert_items(
            [(k, v) for k, v in kwargs.items()])

    def query_origin(self, host):
        _, data_origin = self.tree.open("Janitor", "data_origin", file="IOT").filter(host=host, is_del=0)
        if data_origin:
            data_info = self.tree.open("Janitor", "data_origin\\%s" % data_origin[0], file="IOT").items()
            return data_origin[0], data_info
        return None, {}

    def get_rec_door(self):
        """获取所有的rec_door key"""
        return self.tree.open("Janitor", "rec_door", file="IOT").sub_keys()

    def get_door(self, **kwargs):
        _, data_origin = self.tree.open("Janitor", "door", file="IOT").filter(**kwargs)
        res_dict = {}
        for i in data_origin:
            data_info = self.tree.open("Janitor", "door\\%s" % i, file="IOT").items("rec_id")
            res_dict[data_info["rec_id"]] = i
        return res_dict

    def query_door(self, **kwargs):
        """查找门禁"""
        _, data_origin = self.tree.open("Janitor", "door", file="IOT").filter(**kwargs)

        if data_origin:
            data_info = self.tree.open("Janitor", "door\\%s" % data_origin[0], file="IOT").items()
            return data_origin[0], data_info
        return None, {}

    def get_door_all(self, paging, **kwargs):
        """获取门禁数据"""
        """query_field:查询字段"""
        query_field = ['label', 'model_id', 'origin_id', 'auth_method']

        """
        具体操作
        f_door：查询出的数据
        """
        if kwargs.get('origin_id'):
            """查看门禁"""
            ret = self.tree.open("Janitor", "door", file="IOT") \
                .filter(label__like="*" + kwargs['search_door'] + "*",
                        origin_id=kwargs['origin_id'], is_del=0, **paging)

            if ret[1]:
                f_door = self.tree.open("Janitor", "door", file="IOT").sub_items(key_list=ret[1], prop_list=query_field)
            else:
                f_door = {}
        else:
            """门禁显示"""
            ret = self.tree.open("Janitor", "door", file="IOT") \
                .filter(label__like="*" + kwargs['search_door'] + "*", is_del=0, **paging)
            if kwargs.get('search_door'):
                res_o = self.tree.open("Janitor", "data_origin", file="IOT") \
                    .filter(label__like='*' + kwargs['search_door'] + "*")
                if res_o[1]:
                    """构建查询格式"""
                    j = 0
                    for v in range(len(res_o[1])):
                        if j == 0:
                            expression_temp = '(%s' % str(v)
                        else:
                            expression_temp += ' or ' + str(v)
                        j += 1
                    expression_temp += ')'
                    default_expression = ' or '.join([expression_temp, str(v + 1)])
                    default_expression = '(' + default_expression + ')' + ' and ' + str(v + 2)
                    """进行查询"""
                    ret = self.tree.open("Janitor", "door", file="IOT").filter(origin_id__in=res_o[1],
                                                                               label__like="*" + kwargs[
                                                                                   'search_door'] + "*",
                                                                               is_del=0,
                                                                               default_expression=default_expression,
                                                                               **paging)

            if ret[1]:
                f_door = self.tree.open("Janitor", "door", file="IOT").sub_items(key_list=ret[1], prop_list=query_field)
            else:
                f_door = {}

        """修正品牌或数据源"""
        data_list = []
        page = {}

        x = 1

        for key, val in f_door.items():
            # 添加排序
            if paging:
                val['order_number'] = paging['page_size'] * (paging['page_index'] - 1) + x
            else:
                val['order_number'] = x
            x += 1

            if val.get("auth_method"):
                """修正开门方式名称"""
                origin_door_auth = self.tree.open("Janitor", 'data_origin_conf\\%s\\%s'
                                                  % (val['model_id'], 'auth_method'), file="IOT").items()
                val["auth_method"] = val['auth_method'].split(',')
                val["auth_method"].pop()
                for i, j in enumerate(val['auth_method']):
                    if j in origin_door_auth.keys():
                        val['auth_method'][i] = origin_door_auth[j]
                val['auth_method'] = ",".join(val['auth_method'])

            if val.get('origin_id'):
                """修正数据源名称"""
                val['desc'] = ''
                if kwargs.get('origin_id'):
                    del val['origin_id']
                else:
                    origin_conf_label = self.tree.open("Janitor", 'data_origin\\%s'
                                                       % val['origin_id'], file="IOT").items()
                    val['origin_id'] = origin_conf_label['label']

            if val.get('model_id'):
                """修正模板名称"""
                if not kwargs.get('origin_id'):
                    del val['model_id']
                else:
                    origin_conf_label = self.tree.open("Janitor", 'data_origin_conf\\%s'
                                                       % val['model_id'], file="IOT").items()

                    val['model_id'] = origin_conf_label['label']

            if type(val) is dict:
                """修正ID键值对"""
                val['door_id'] = key
                val['mxdevicetype'] = "janitor"
                data_list.append(val)
            else:
                """分类杂乱数据"""
                page[key] = val
        if page:
            """添加杂乱数据"""
            data_list.append(page)

        return ret[0], data_list

    def retrieve(self, code):
        """
        获取门禁的基础信息
        @return:
        """
        query_field = []
        try:

            data = self.tree.open("Janitor", "door\\%s" % code, file="IOT").items(query_field)
            data["code"] = code
            if data.get("is_del", 1):
                raise VerifyError(_("查询设备错误"))
        except DBError as e:
            logging.error(e)
            raise VerifyError(_("查询设备错误"))
        return data
